var Tv_Arte_Generator;
(function()
{

    Tv_Arte_Generator =
	{

	    _formData:{},
	    _IMG_MAX_HEIGHT:40,
	    _searchTimeout:null,
		_resizeTimeout:null,
		_centerizeTimeout:null,
		
		_showState:function(i)
		{
		    $('.step')
				.show()
				.filter(function(k, v) { return k > i-1; })
				.hide();
		},

		_setImage:function()
		{
      		var $img = $('.dropzone img'), w, h;
      		if ($img.height() > SELF._IMG_MAX_HEIGHT) {
      		    w = Math.round($img.width() * SELF._IMG_MAX_HEIGHT / $img.height());
      		    h = SELF._IMG_MAX_HEIGHT;
      		} else {
      		    w = $img.width();
      		    h = $img.height();
      		}
      		$img
			 	.attr('width', w)
				.attr('height', h);
      		SELF._formData.imageW = w;
 			SELF._formData.imageH = h;
 			SELF._formData.imageUrl = $img.attr('src');
  		},

		initialize:function()
		{
			$(document).ready(SELF.onDocumentReady);
		},

		onDocumentReady:function(event)
		{
			SELF.state1();
	    	$('#search').keyup(SELF.onSearchType);
	    	$('#dialog-code a').click(function(event)
	    	{
	    	    event.preventDefault();
	    	    SELF.uncenterize('#dialog-code');
	    	});
	    	$('#dialog-xml a').click(function(event)
	    	{
	    	    event.preventDefault();
	    	    SELF.uncenterize('#dialog-xml');
	    	});
	    	$('#dialog-preview a').click(function(event)
	    	{
	    	    event.preventDefault();
	    	    SELF.uncenterize('#dialog-preview');
	    	});
      		SELF.uncenterize('#dialog-code');
      		SELF.uncenterize('#dialog-xml');
      		SELF.uncenterize('#dialog-preview');
      		$('#generate').click(function(event) {
      		    event.preventDefault();
				$.ajax('./httpservice.php/?event=generate', {
					success:function(e) {

					},
					type:'POST',
					data:''
				});
      		});
		},

    	modalize:function()
    	{
			if ($('#overlay').length == 0) {
			    $('body').prepend('<div id="overlay"></div>');
			}
			$('body').css({overflow:'hidden'});
			$(window).unbind('resize').bind('resize', function(event)
			{
			    clearTimeout(SELF._resizeTimeout);
			    SELF._resizeTimeout = setTimeout(function()
			    {
			        $('#overlay').css({
			            zIndex:1000,
			            left:0,
			            top:0,
			            position:'absolute',
			            width:$(window).width() + 'px',
			            height:$(window).height() + 'px',
			            backgroundColor:'#aaa',
			            opacity:.5
			    	});
			    }, 50);
			}).trigger('resize');
    	},
    	
    	unmodalize:function()
    	{
    	    clearTimeout(SELF._resizeTimeout);
    	    $('#overlay').remove();
    	    $('body').css({overflow:'auto'});
    	},
    	
    	_centerize:function()
     	{
          	clearTimeout(SELF._centerizeTimeout);
          	SELF._centerizeTimeout = setTimeout(function()
          	{
	          	$(SELF._centerize_selector)
					.css({
						position:'absolute',
						display:'inline-block',
						zIndex:1001
                    })
					.animate({
						top:$(window).height() * .5 - $(SELF._centerize_selector).outerHeight() * .5 + 'px',
						left:$(window).width() * .5 - $(SELF._centerize_selector).outerWidth() * .5 + 'px'
					}, 100);
          	}, 50);
    	},
    	
    	centerize:function(selector)
    	{
    	    SELF.modalize();
    	    SELF._centerize_selector = selector;
    	    $(selector).show();
    	    $(window).unbind('resize', SELF._centerize).bind('resize', SELF._centerize).trigger('resize');
    	},
    	
    	uncenterize:function(selector)
    	{
    	    SELF.unmodalize();
    	    $(window).unbind('resize', SELF._centerize);
    	    $(selector).hide();
    	},
    	
    	showEmbedCode:function(UID)
    	{
    	    $.ajax('./httpservice.php/?event=getCode', {
				success:function(e) {
			        $('#dialog-code-content').html(e);
			        SELF.centerize('#dialog-code');
				},
				type:'POST',
				data:{UID:UID}
			});
    	    /*$.ajax('./httpservice.php/?event=getEmbedCode', {
				success:function(e) {
			        $('#embed-code-js').val(e);
			        SELF.centerize('#dialog-code');
			        $.ajax('./httpservice.php/?event=getCacheableEmbedCode', {
						success:function(e) {
		           			$('#embed-cacheablecode-js').val(e);
						},
						type:'POST',
						data:{UID:UID}
					});
				},
				type:'POST',
				data:{UID:UID}
			});
            $.ajax('./httpservice.php/?event=getCachedFiles', {
				success:function(e) {
					$('#static-files').html(e);
				},
				type:'POST',
				data:{UID:UID}
			});*/
    	},
    	
    	showXml:function(path)
    	{
    	    $.ajax('./httpservice.php/?event=getXml', {
				success:function(e) {
				    var data = JSON.parse(e);
				    $('#dialog-xml h2').html(data.path);
			        $('#xml-textarea').val(data.xml);
			        SELF.centerize('#dialog-xml');
				},
				type:'POST',
				data:{path:path}
			});
    	},
    	
    	showPreview:function(src)
    	{
         	$('#dialog-preview').css({width:'1024px', height:'90%'});
    	    SELF.centerize('#dialog-preview');
    	    $('#iframe-preview').attr('src', src).attr('width', 1000);
    	},
    	
        onSearchType:function(event)
        {
            clearTimeout(SELF._searchTimeout);
            if ($('#search').val().length == 0) return;
            SELF._searchTimeout = setTimeout(function()
			{
			    $.ajax('./httpservice.php?event=search', {
					success:function(e)
					{
					    if (e.length > 0) {
                            $('#search-result').show().html(e);
					    } else {
					        $('#search-result').hide();
					    }
					},
					type:'POST',
					data:{query:$('#search').val()}
				});
			}, 250);
        },
        
		state1_onSiteClick:function(event)
		{
            $('.sitelist li')
				.removeClass('selected');
			$(this)
				.parent()
				.parent()
				.attr('class', 'selected');
            SELF.state2();
		},

		state1:function()
		{
        	SELF._showState(1);
	        $('.sitelist li input').removeAttr('checked')
				.unbind('click')
				.bind('click', SELF.state1_onSiteClick)
				.css({cursor:'pointer'});
		},

		state2_onKeyUp:function(event)
        {
            var s = '';
            $('.step:eq(1) input[type="text"]').each(function()
            {
                s += $(this).val();
			});
   			if (s.length > 0) {
   			    SELF.state3();
   			} else {
   			    SELF.state2();
   			}
        },

		state2:function()
		{
		    SELF._showState(2);
            $('.step:eq(1) input[type="text"]')
				.attr('disabled', 'disabled')
				.val('Loading...');
            $.ajax('./httpservice.php?event=getUrls', {
				success:function(e)
				{
			    	var data = JSON.parse(e);
			    	for (var lang in data.urls) {
			        	$('#url_' + lang).val(data.urls[lang]);
			        	$('#urlExtra_' + lang).val(data.urls[lang]);
			        	$('#titleExtra_' + lang).val(data.titles[lang]);
			    	}
			    	$('.dropzone').html('<img src="' + data.imageUrl + '" alt="" />');
			    	$('.dropzone img').load(function(event)
			    	{
                        SELF._setImage();
			    	});
			    	$('.step:eq(1) input[type="text"]')
						.removeAttr('disabled')
   						.trigger('keyup');
				},
				type:'POST',
				data:{siteType:$('input:radio[name="siteType"]:checked').val()}
			});
            $('.step:eq(1) input[type="text"]')
				.unbind('keyup')
				.bind('keyup', SELF.state2_onKeyUp);
		},

		state3_onDragOver:function(event)
		{
		    event.originalEvent.stopPropagation();
    		event.originalEvent.preventDefault();
		},

		state3_onDrop:function(event)
		{
		    SELF._formData.imageData = '';
			event.originalEvent.stopPropagation();
	    	event.originalEvent.preventDefault();
		 	var files = event.originalEvent.dataTransfer.files; // FileList object.
		    if (files.length == 1 && files[0].type.match('image.*')) {
		 		var fr = new FileReader();
		 		fr.onload = function(event)
		 		{
		 			SELF._formData.imageData = event.target.result;
		 			$('.dropzone').html('<img src="' + SELF._formData.imageData + '" alt="" />');
		 			var $img = $('.dropzone img');
		 			$('.dropzone img').load(function(event) {
						SELF._setImage();
	 				});
	 			};
		 		fr.readAsDataURL(files[0]);
		 	}
		},

		state3_onKeyUp:function(event)
        {
            var s = '';
            $('.step:eq(2) input[type="text"]').each(function()
            {
                s += $(this).val();
			});
   			if (s.length > 0) {
   			    SELF.state4();
   			} else {
   			    SELF.state3();
   			}
        },

		state3:function()
		{
		    SELF._showState(3);
		    SELF._formData.imageData = '';
		    $('.dropzone')
				.unbind('drop')
				.unbind('dragover')
				.bind('drop', SELF.state3_onDrop)
				.bind('dragover', SELF.state3_onDragOver);
            $('.step:eq(2) input[type="text"]')
				.unbind('keyup')
				.bind('keyup', SELF.state3_onKeyUp)
				.trigger('keyup');
		},

        state4_onSubmit:function(event)
        {
            event.preventDefault();
            delete SELF._formData.showLogin;
            delete SELF._formData.showSocial;
            $.each($('#embed-form').serializeArray(), function(k, v)
            {
                SELF._formData[v.name] = v.value;
            });
	    	$.ajax('./httpservice.php/?event=save', {
				success:function(e) {
                    var data = JSON.parse(e);
			        //$('#embed-code-js').val(data.code);
			        SELF.state1();
			        //SELF.centerize('#dialog-code');
			        
			        SELF.showEmbedCode(data.UID);
			        
				},
				type:'POST',
				data:{json:JSON.stringify(SELF._formData)}
			});
        },

		state4:function()
		{
	         SELF._showState(4);
	         $('#embed-form')
			 	.unbind('submit')
				.bind('submit', SELF.state4_onSubmit);
		}

	};

	var SELF = Tv_Arte_Generator;

})();